package com.diyizu.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diyizu.youdianda.common.R;
import com.diyizu.youdianda.dto.*;
import com.diyizu.youdianda.entity.*;
import com.diyizu.youdianda.mapper.YddArticleMapper;
import com.diyizu.youdianda.service.*;
import com.diyizu.youdianda.util.JwtUtils;
import com.diyizu.youdianda.util.UserID;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/index")
@Slf4j
public class IndexController {

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private YddAdvposService yddAdvposService;
    @Autowired
    private YddTagService yddTagService;
    @Autowired
    private YddArticleService yddArticleService;
    @Autowired
    private YddCateService yddCateService;
    @Autowired
    private YddAdvimgService yddAdvimgService;
    @Autowired
    private YddUserService yddUserService;
    @Autowired
    private YddLinkService yddLinkService;
    @Autowired
    private YddUserDataService yddUserDataService;
    @Autowired
    private YddArticleMapper yddArticleMapper;

    @GetMapping("/getConfig")
    public R getConfig() {

        LambdaQueryWrapper<SysConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysConfig::getTabValue, "system");
        List<SysConfig> sysConfigs = sysConfigService.list(lqw);

        Map<String, String> hashMap = new HashMap<>();
        for (SysConfig sysConfig : sysConfigs) {
            hashMap.put(sysConfig.getAttrKey(), sysConfig.getAttrValue());
        }

        return R.success(hashMap);
    }

    @PostMapping("/login")
    public R login(@RequestBody SysUser sysUser) {
        String login_name = sysUser.getLoginName();
        String pwd = sysUser.getPassword();
        String password = DigestUtils.md5DigestAsHex(pwd.getBytes());

        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Strings.isNotEmpty(login_name), SysUser::getLoginName, login_name);
        SysUser user = sysUserService.getOne(lqw);

        if (user == null) {
            return R.error("该账号不存在");
        }

        if (!password.equals(user.getPassword())) {
            return R.error("密码错误");
        }

        HashMap<String, String> map = new HashMap<>();
        map.put("id", user.getId());
        String token = JwtUtils.getToken(map);

        HashMap<String, String> reMap = new HashMap<>();
        reMap.put("token", token);
        return R.success(reMap);
    }

    @PostMapping("/profile")
    public R profile(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("x-token");
        String id = null;
        if (JwtUtils.verifyToken(token)) {
            Claims claims = JwtUtils.getClaims(token);
            id = (String) claims.get("id");
        } else {
            return R.error("用户信息已过期");
        }


        Profile profile = new Profile();
        //userInfo
        SysUser sysUser = sysUserService.getById(id);
        SysUserDto sysUserDto = new SysUserDto();
        BeanUtils.copyProperties(sysUser, sysUserDto);

        String s1 = sysUser.getRoleId();
        String s2 = s1.substring(2, s1.length() - 2);
        String[] roleId = s2.split("\",\"");
        sysUserDto.setRole_id(roleId);
        //menuList
        List<SysMenu> menuList = new ArrayList<>();
        List<String> roleList = new ArrayList<>();
        for (String s : roleId) {
            SysRole sysRole = sysRoleService.getById(s);

            if (sysRole.getSuperadmin() == 1) {
                //1.按菜单id找pid返回
                List<SysMenu> allMenus = sysMenuService.list();
                for (SysMenu sysMenu : allMenus) {
                    if (!sysMenu.getMark().contains("@")) {
                        menuList.add(sysMenu);
                    }
                }

                //or
//                LambdaQueryWrapper<SysMenu> adminMenu = new LambdaQueryWrapper<>();
//                adminMenu.like(SysMenu::getComponent,"layout");
//                List<SysMenu> list1 = sysMenuService.list(adminMenu);
//                for (SysMenu sysMenu : list1) {
//                    LambdaQueryWrapper<SysMenu> adminPidMenu = new LambdaQueryWrapper<>();
//                    adminPidMenu.eq(SysMenu::getPid,sysMenu.getId());
//                    List<SysMenu> list2 = sysMenuService.list(adminPidMenu);
//                    for (SysMenu menu : list2) {
//                        menuset.add(menu);
//                    }
//                }
                //2,按关系表返回
            } else {
                LambdaQueryWrapper<SysRoleMenu> lqw = new LambdaQueryWrapper<>();
                lqw.eq(SysRoleMenu::getRoleId, sysRole.getId());
                List<SysRoleMenu> roleMenus = sysRoleMenuService.list(lqw);

                for (SysRoleMenu roleMenu : roleMenus) {
                    LambdaQueryWrapper<SysMenu> qw = new LambdaQueryWrapper<>();
                    qw.eq(SysMenu::getId, roleMenu.getMenuId());
                    List<SysMenu> menus = sysMenuService.list(qw);
                    for (int i = 0; i < menus.size(); i++) {
                        if (Strings.isNotEmpty(menus.get(i).getPath())) {
                            menuList.add(menus.get(i));
                        }
                    }
                }
            }


            roleList.add(sysRole.getName());
        }
        sysUserDto.setRolename(roleList);
        profile.setUserInfo(sysUserDto);


        //会员管理
//        SysMenu huiyuan = sysMenuService.getById(138);
//        menuset.add(huiyuan);
//        LambdaQueryWrapper<SysMenu> menuQw = new LambdaQueryWrapper<>();
//        menuQw.eq(SysMenu::getPid,138);
//        List<SysMenu> sysMenus = sysMenuService.list(menuQw);
//        for (SysMenu sysMenu : sysMenus) {
//            menuset.add(sysMenu);
//        }
//        //友情链接管理
//        SysMenu youqin = sysMenuService.getById(137);
//        menuset.add(youqin);
//        //修改文章
//        SysMenu wenzhang = sysMenuService.getById(136);
//        menuset.add(wenzhang);

        profile.setMenuList(menuList);


        HashMap<String, Map<String, String>> map = new HashMap<>();

        LambdaQueryWrapper<SysDict> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(SysDict::getType, "table_type");
        List<SysDict> sysDicts1 = sysDictService.list(qw1);
        HashMap<String, String> hashMap1 = new HashMap<>();
        for (SysDict sysDict : sysDicts1) {
            hashMap1.put(sysDict.getValue(), sysDict.getLabel());
        }
        map.put("table_type", hashMap1);

        LambdaQueryWrapper<SysDict> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(SysDict::getType, "interface_type");
        List<SysDict> sysDicts2 = sysDictService.list(qw2);
        HashMap<String, String> hashMap2 = new HashMap<>();
        for (SysDict sysDict : sysDicts2) {
            hashMap2.put(sysDict.getValue(), sysDict.getLabel());
        }
        map.put("interface_type", hashMap2);

        LambdaQueryWrapper<SysDict> qw3 = new LambdaQueryWrapper<>();
        qw3.eq(SysDict::getType, "report_type");
        List<SysDict> sysDicts3 = sysDictService.list(qw3);
        HashMap<String, String> hashMap3 = new HashMap<>();
        for (SysDict sysDict : sysDicts3) {
            hashMap3.put(sysDict.getValue(), sysDict.getLabel());
        }
        map.put("report_type", hashMap3);

        LambdaQueryWrapper<SysDict> qw4 = new LambdaQueryWrapper<>();
        qw4.eq(SysDict::getType, "theme");
        List<SysDict> sysDicts4 = sysDictService.list(qw4);
        HashMap<String, String> hashMap4 = new HashMap<>();
        for (SysDict sysDict : sysDicts4) {
            hashMap4.put(sysDict.getValue(), sysDict.getLabel());
        }
        map.put("theme", hashMap4);

        LambdaQueryWrapper<SysDict> qw5 = new LambdaQueryWrapper<>();
        qw5.eq(SysDict::getType, "order_type");
        List<SysDict> sysDicts5 = sysDictService.list(qw5);
        HashMap<String, String> hashMap5 = new HashMap<>();
        for (SysDict sysDict : sysDicts5) {
            hashMap5.put(sysDict.getValue(), sysDict.getLabel());
        }
        map.put("order_type", hashMap5);
        profile.setDictsList(map);
        //?* ???
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("*");
        profile.setBtnList(arrayList);

        return R.success(profile);
    }

    @GetMapping("/baseInfo")
    public R baseInfo() {
        HashMap<String, Object> map = new HashMap<>();

        List<YddCate> yddCates = yddCateService.list();
        List<YddCateDto> yddCateDtos = yddCates.stream().map(item -> {
            YddCateDto yddCateDto = new YddCateDto();
            BeanUtils.copyProperties(item, yddCateDto);

            LambdaQueryWrapper<YddArticle> articleQw = new LambdaQueryWrapper<>();
            articleQw.eq(YddArticle::getCateid, item.getId());
            int num = yddArticleService.count(articleQw);

            yddCateDto.setNum(num);
            return yddCateDto;
        }).collect(Collectors.toList());
        map.put("all_cate", yddCateDtos);

        int advpos_num = yddAdvposService.count();
        map.put("advpos_num", advpos_num);

        int tag_num = yddTagService.count();
        map.put("tag_num", tag_num);

        int admin_num = sysUserService.count();
        map.put("admin_num", admin_num);

        int article_num = yddArticleService.count();
        map.put("article_num", article_num);

        int cate_num = yddCateService.count();
        map.put("cate_num", cate_num);

        int advimg_num = yddAdvimgService.count();
        map.put("advimg_num", advimg_num);

        ArrayList<YddUser> yddUsers = new ArrayList<>();
        int user_num = yddUserService.count();
        for (int i = 0; i < 7; i++) {
            Random r = new Random();
            int id = r.nextInt(user_num);
            YddUser yddUser = yddUserService.getById(id);
            if (yddUser == null) {
                i--;
                continue;
            } else {
                yddUsers.add(yddUser);
            }
        }
        map.put("new_user", yddUsers);

        ArrayList<YddArticle> yddArticles = new ArrayList<>();
        LambdaQueryWrapper<YddArticle> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(YddArticle::getLovenum);
        List<YddArticle> yddArticleList = yddArticleService.list(lqw);
        for (int i = 1; i < 8; i++) {
            yddArticles.add(yddArticleList.get(i));
        }
        map.put("hot_article", yddArticles);

        HashMap<String, Integer> hashMap = new HashMap<>();
        LambdaQueryWrapper<YddUser> manqw = new LambdaQueryWrapper<>();
        manqw.eq(YddUser::getSex, 0);
        int man = yddUserService.count(manqw);

        LambdaQueryWrapper<YddUser> womanqw = new LambdaQueryWrapper<>();
        womanqw.eq(YddUser::getSex, 1);
        int woman = yddUserService.count(womanqw);

        int total = man + woman;

        hashMap.put("total", total);
        hashMap.put("user_man", man);
        hashMap.put("user_woman", woman);
        map.put("user", hashMap);

        return R.success(map);

    }

    /**
     * 前台首页
     * @return
     */
    @GetMapping("/index")
    public R<HashMap<String, Object>> index() {
        HashMap<String, Object> hashMap = new HashMap<>();
        //Allcate集合中查询
        LambdaQueryWrapper<YddCate> qw1 = new LambdaQueryWrapper<>();
        qw1.orderByDesc(YddCate::getSortNum);
        List<YddCate> allCate = yddCateService.list(qw1);
        log.info("allCate = {}", allCate);
        hashMap.put("allCate", allCate);

        SysConfigDto sysConfigDto = new SysConfigDto();
        //list
        //base
        ListArray baseList = new ListArray();
        baseList.setName("基础配置");
        baseList.setKey("base");

        ListChildren baseChildren1 = new ListChildren();
        baseChildren1.setName("站点配置");
        LambdaQueryWrapper<SysConfig> baseQw1 = new LambdaQueryWrapper<>();
        baseQw1.eq(SysConfig::getGroupValue, "站点配置");
        baseQw1.orderByAsc(SysConfig::getSortNum);
        List<SysConfig> zhanDian = sysConfigService.list(baseQw1);

        List<SysConfigDto> zhanDian2 = zhanDian.stream().map(item->{
            SysConfigDto configDto = new SysConfigDto();
            BeanUtils.copyProperties(item,configDto);

            if (Strings.isNotEmpty(item.getConfigValue())){
                ArrayList<Map> list = new ArrayList<>();
                String sub = item.getConfigValue();
                //String substring = sub1.substring(2, roleId.length() - 2);
                String[] split = sub.split("&");
                for (String s : split) {
                    String[] strings = s.split("=");
                    Map<String, String> map = new HashMap<>();
                    map.put("label",strings[0]);
                    map.put("value",strings[1]);
                    list.add(map);
                }
                configDto.setConfig_value(list);
            }

            return configDto;
        }).collect(Collectors.toList());

        baseChildren1.setData(zhanDian2);

        ListChildren baseChildren2 = new ListChildren();
        baseChildren2.setName("底部信息");
        LambdaQueryWrapper<SysConfig> baseQw2 = new LambdaQueryWrapper<>();
        baseQw2.eq(SysConfig::getGroupValue, "底部信息");
        baseQw2.orderByAsc(SysConfig::getSortNum);
        List<SysConfig> diBu = sysConfigService.list(baseQw2);
        baseChildren2.setData(diBu);

        ListChildren baseChildren3 = new ListChildren();
        baseChildren3.setName("其他配置");
        LambdaQueryWrapper<SysConfig> baseQw3 = new LambdaQueryWrapper<>();
        baseQw3.eq(SysConfig::getGroupValue, "其他配置");
        baseQw3.orderByAsc(SysConfig::getSortNum);
        List<SysConfig> qiTa = sysConfigService.list(baseQw3);
        baseChildren3.setData(qiTa);

        ArrayList<ListChildren> BaseChildrens = new ArrayList<>();
        BaseChildrens.add(baseChildren1);
        BaseChildrens.add(baseChildren2);
        BaseChildrens.add(baseChildren3);
        baseList.setChildren(BaseChildrens);

        //system
        ListArray systemList = new ListArray();
        systemList.setName("系统配置");
        systemList.setKey("system");

        ListChildren systemChildren1 = new ListChildren();
        systemChildren1.setName("管理系统配置");
        LambdaQueryWrapper<SysConfig> systemQw1 = new LambdaQueryWrapper<>();
        systemQw1.eq(SysConfig::getGroupValue, "管理系统配置");
        systemQw1.orderByAsc(SysConfig::getSortNum);
        List<SysConfig> guanLi = sysConfigService.list(systemQw1);
        systemChildren1.setData(guanLi);

        ArrayList<ListChildren> systemChildrens = new ArrayList<>();
        systemChildrens.add(systemChildren1);
        systemList.setChildren(systemChildrens);

        //custom
        ListArray customList = new ListArray();
        customList.setName("其他设置");
        customList.setKey("custom");

        ListChildren customChildren1 = new ListChildren();
        customChildren1.setName("通知公告");
        LambdaQueryWrapper<SysConfig> customQw1 = new LambdaQueryWrapper<>();
        customQw1.eq(SysConfig::getGroupValue, "通知公告");
        customQw1.orderByAsc(SysConfig::getSortNum);
        List<SysConfig> tongZhi = sysConfigService.list(customQw1);
        customChildren1.setData(tongZhi);

        ListChildren customChildren2 = new ListChildren();
        customChildren2.setName("前台图片");
        LambdaQueryWrapper<SysConfig> customQw2 = new LambdaQueryWrapper<>();
        customQw2.eq(SysConfig::getGroupValue, "前台图片");
        customQw2.orderByAsc(SysConfig::getSortNum);
        List<SysConfig> qianTai = sysConfigService.list(customQw2);
        customChildren2.setData(qianTai);

        ArrayList<ListChildren> customChildrens = new ArrayList<>();
        customChildrens.add(customChildren1);
        customChildrens.add(customChildren2);
        customList.setChildren(customChildrens);

        ArrayList<ListArray> list = new ArrayList<>();
        list.add(baseList);
        list.add(systemList);
        list.add(customList);
        sysConfigDto.setList(list);

        //allData
        LambdaQueryWrapper<SysConfig> allDataQw = new LambdaQueryWrapper<>();
        allDataQw.orderByAsc(SysConfig::getSortNum);
        List<SysConfig> sysConfigs = sysConfigService.list(allDataQw);
        sysConfigDto.setAllData(sysConfigs);

        hashMap.put("config",sysConfigDto);

        //AllTag集合查询
        List<YddTag> allTag = yddTagService.list();
        log.info("allTag = {}", allTag);
        hashMap.put("allTag", allTag);

        //AllLink集合查询
        List<YddLink> allLink = yddLinkService.list();
        log.info("allLink = {}", allLink);
        hashMap.put("allLink", allLink);

        //Banner集合查询
        List<YddAdvimg> allBanner = yddAdvimgService.list();
        //创建banner集合
        List<YddAdvimg> banner = new ArrayList<>();
        //创建sideBanner集合
        List<YddAdvimg> sideBanner = new ArrayList<>();
        //创建showBanner集合
        List<YddAdvimg> showBanner = new ArrayList<>();
        log.info("allBanner = {}", allBanner);
        //获取advimgpos判断属于哪一个banner
        for (int i = 0; i < allBanner.size(); i++) {
            String advimgpos = allBanner.get(i).getAdvimgpos();
            if ("15".equals(advimgpos)) {
                banner.add(allBanner.get(i));
            } else if ("14".equals(advimgpos)) {
                sideBanner.add(allBanner.get(i));
            } else {
                showBanner.add(allBanner.get(i));
            }
        }
        hashMap.put("banner", banner);
        hashMap.put("sideBanner", sideBanner);
        hashMap.put("showBanner", showBanner);
//
//        //config集合查询
//        HashMap<String, Object> config = new HashMap<>();
//        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
//
//        //一层children查询条件
//        LambdaQueryWrapper<SysConfig> wrapper1 = new LambdaQueryWrapper();
//        wrapper1.eq(SysConfig::getTabValue, "base");
//        wrapper1.orderByAsc(SysConfig::getSortNum);
//        //执行查询
//        List<SysConfig> base = sysConfigService.list(wrapper1);
//        log.info("base = {}", base);
//
//        //一层children查询
//        HashMap<String, Object> children1 = new HashMap<>();
//        ArrayList<HashMap<String, Object>> baseList = new ArrayList<>();
//        HashMap<String, Object> hashMap1 = new HashMap<>();
//        ArrayList<SysConfig> baseList1 = new ArrayList<>();
//        HashMap<String, Object> hashMap2 = new HashMap<>();
//        ArrayList<SysConfig> baseList2 = new ArrayList<>();
//        HashMap<String, Object> hashMap3 = new HashMap<>();
//        ArrayList<SysConfig> baseList3 = new ArrayList<>();
//        for (int i = 0; i < base.size(); i++) {
//            String groupValue = base.get(i).getGroupValue();
//            if ("站点配置".equals(groupValue)) {
//                baseList1.add(base.get(i));
//            } else if ("站点配置".equals(groupValue)) {
//                baseList2.add(base.get(i));
//            } else if ("其他配置".equals(groupValue)) {
//                baseList3.add(base.get(i));
//
//            }
//        }
//        hashMap1.put("name", "站点配置");
//        hashMap1.put("data", baseList1);
//        hashMap2.put("name", "底部信息");
//        hashMap2.put("data", baseList2);
//        hashMap3.put("name", "其他配置");
//        hashMap3.put("data", baseList3);
//        baseList.add(hashMap1);
//        baseList.add(hashMap2);
//        baseList.add(hashMap3);
//        children1.put("name", "基础配置");
//        children1.put("key", "base");
//        children1.put("children", baseList);
//        list.add(children1);
//
//        //二层children查询
//        LambdaQueryWrapper<SysConfig> wrapper2 = new LambdaQueryWrapper();
//        wrapper2.eq(SysConfig::getTabValue, "system");
//        wrapper2.orderByAsc(SysConfig::getSortNum);
//        //执行查询
//        List<SysConfig> system = sysConfigService.list(wrapper2);
//        log.info("system = {}", system);
//
//        //二层children查询
//        HashMap<String, Object> children2 = new HashMap<>();
//        ArrayList<HashMap<String, Object>> systemList = new ArrayList<>();
//        HashMap<String, Object> systemHashMap = new HashMap<>();
//        systemHashMap.put("name", "管理系统配置");
//        systemHashMap.put("data", system);
//        children2.put("name", "系统设置");
//        children2.put("key", "system");
//        children2.put("children", systemHashMap);
//        list.add(children2);
//
//        //三层children查询
//        LambdaQueryWrapper<SysConfig> wrapper3 = new LambdaQueryWrapper();
//        wrapper2.eq(SysConfig::getTabValue, "custom");
//        wrapper2.orderByAsc(SysConfig::getSortNum);
//        //执行查询
//        List<SysConfig> custom = sysConfigService.list(wrapper3);
//        log.info("custom = {}", custom);
//
//
//        HashMap<String, Object> children3 = new HashMap<>();
//        ArrayList<HashMap<String, Object>> customList = new ArrayList<>();
//        HashMap<String, Object> customHashMap1 = new HashMap<>();
//        ArrayList<SysConfig> customList1 = new ArrayList<>();
//        HashMap<String, Object> customHashMap2 = new HashMap<>();
//        ArrayList<SysConfig> customList2 = new ArrayList<>();
//        for (int i = 0; i < custom.size(); i++) {
//            String groupValue = custom.get(i).getGroupValue();
//            if ("通知公告".equals(groupValue)) {
//                customList1.add(custom.get(i));
//            } else if ("前台图片".equals(groupValue)) {
//                customList2.add(custom.get(i));
//            }
//        }
//        customHashMap1.put("name", "通知公告");
//        customHashMap1.put("data", customList1);
//        customHashMap2.put("name", "前台图片");
//        customHashMap2.put("data", customList2);
//        customList.add(customHashMap1);
//        customList.add(customHashMap2);
//        children3.put("name", "其他设置");
//        children3.put("key", "custom");
//        children3.put("children", customList);
//        list.add(children3);
//
//
//        //将数据封装至config集合中
//        config.put("list", list);
//        //AllData
//        LambdaQueryWrapper<SysConfig> wrapper4 = new LambdaQueryWrapper<>();
//        wrapper4.orderByDesc(SysConfig::getSortNum);
//        List<SysConfig> allData = sysConfigService.list(wrapper4);
//        config.put("allData", allData);
//
//        //将数据封装到hashMap集合中
//        hashMap.put("config", config);
        return R.success(hashMap);

    }

    @GetMapping("/show")
    public R<Map<String,Object>> show(Integer id){

        List<YddArticle> yddArticles = yddArticleService.list();
        YddArticle first = yddArticles.get(0);
        int firstId = first.getId();
        YddArticle last = yddArticles.get(yddArticles.size()-1);
        int lastId = last.getId();

        HashMap<String, Object> map = new HashMap<>();
        YddArticle now=yddArticleService.getById(id);
        //prev要判断上一篇是否还在
        int prevId=id;
        Boolean flag=true;
        while (flag){
            prevId--;
            YddArticle prev=yddArticleService.getById(prevId);
            if (prev!=null){
                HashMap<String,Object> prevMap = new HashMap<>();
                prevMap.put("id",prev.getId());
                prevMap.put("title",prev.getTitle());

                ArrayList<Map> prevList = new ArrayList<>();
                prevList.add(prevMap);
                map.put("prev",prevList);
                break;
            }
            if (prevId+1==firstId){
                HashMap<String,Object> prevMap = new HashMap<>();
                prevMap.put("id",now.getId());
                prevMap.put("title",now.getTitle());

                ArrayList<Map> prevList = new ArrayList<>();
                prevList.add(prevMap);
                map.put("prev",prevList);
                break;
            }
        }

        //next判断下一篇是否还在
        int nextId=id;
        Boolean flag2=true;
        while (flag2){
            nextId++;
            YddArticle next=yddArticleService.getById(nextId);
            if (next!=null){
                HashMap<String,Object> prevMap = new HashMap<>();
                prevMap.put("id",next.getId());
                prevMap.put("title",next.getTitle());

                ArrayList<Map> prevList = new ArrayList<>();
                prevList.add(prevMap);
                map.put("next",prevList);
                break;
            }
            if (nextId-1==lastId){
                HashMap<String,Object> prevMap = new HashMap<>();
                prevMap.put("id",now.getId());
                prevMap.put("title",now.getTitle());

                ArrayList<Map> prevList = new ArrayList<>();
                prevList.add(prevMap);
                map.put("next",prevList);
                break;
            }
        }


        //info
        YddArticleDto yddArticleDto = new YddArticleDto();

        YddArticle info = yddArticleService.getById(id);
        BeanUtils.copyProperties(info,yddArticleDto);

        YddCate Yddcate = yddCateService.getById(info.getCateid());
        yddArticleDto.setCatename(Yddcate.getCatename());

        String uid = UserID.getCurrentId();
        if (uid==null){
            yddArticleDto.setLike(false);
            yddArticleDto.setCollect(false);
        }else {
            int userId=Integer.parseInt(uid);
            LambdaQueryWrapper<YddUserData> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Strings.isNotEmpty(uid),YddUserData::getUserId,userId);
            lqw.eq(YddUserData::getType,2);
            List<YddUserData> likeList = yddUserDataService.list(lqw);
            if (likeList==null){
                yddArticleDto.setLike(false);
            }else {
                for (YddUserData yddUserData : likeList) {
                    if (id==yddUserData.getArticleId()){
                        yddArticleDto.setLike(true);
                    }
                }
            }

            LambdaQueryWrapper<YddUserData> cqw = new LambdaQueryWrapper<>();
            cqw.eq(YddUserData::getUserId,Integer.parseInt(uid));
            cqw.eq(YddUserData::getType,1);
            List<YddUserData> zanList = yddUserDataService.list(cqw);
            if (zanList==null){
                yddArticleDto.setCollect(false);
            }else {
                for (YddUserData yddUserData : zanList) {
                    if (id==yddUserData.getArticleId()){
                        yddArticleDto.setCollect(true);
                    }
                }
            }
        }
        map.put("info", yddArticleDto);
        //recommend
        ArrayList<Map> hotList = new ArrayList<>();

        LambdaQueryWrapper<YddArticle> hotQw = new LambdaQueryWrapper<>();
        hotQw.eq(YddArticle::getIshot,1);
        List<YddArticle> hots = yddArticleService.list(hotQw);
        int a=0;
        for (YddArticle hot : hots) {
            if (a<8) {
                HashMap<String, Object> hotMap = new HashMap<>();
                YddCate cate = yddCateService.getById(hot.getCateid());
                hotMap.put("catename",cate.getCatename());
                hotMap.put("id",hot.getId());
                hotMap.put("title",hot.getTitle());
                hotMap.put("pic",hot.getPic());
                hotMap.put("cateid",hot.getCateid());
                hotList.add(hotMap);
                a++;
            }else {
                break;
            }
        }
        map.put("recommend",hotList);

        return R.success(map);
    }

    @GetMapping("/new")
    public R hotarticle(int page, int limit){
        HashMap<String, Object> map = new HashMap<>();
        map.put("desc","首页大列表");

        long hour = System.currentTimeMillis()-86400000;
        LambdaQueryWrapper<YddArticle> lqw = new LambdaQueryWrapper<>();
        lqw.gt(YddArticle::getCreateDate,hour);
        int num_day = yddArticleService.count(lqw);
        map.put("num_day",num_day);

        long week = System.currentTimeMillis()-604800000;
        LambdaQueryWrapper<YddArticle> qw = new LambdaQueryWrapper<>();
        qw.gt(YddArticle::getCreateDate,hour);
        int num_week = yddArticleService.count(qw);
        map.put("num_week",num_week);

        //分页构造器
        Page<YddArticle> pageInfo = new Page<>(page, limit);
        yddArticleService.page(pageInfo);
        if (page!=1&&pageInfo.getRecords().size()==0){
            pageInfo = new Page<>(page-1, limit);
            yddArticleService.page(pageInfo,lqw);
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("count",pageInfo.getTotal());
        hashMap.put("totalPages",pageInfo.getPages());
        hashMap.put("pageSize",limit);
        hashMap.put("currentPage",page);

        List<YddArticleDto> data = pageInfo.getRecords().stream().map(item -> {
            YddArticleDto yddArticleDto = new YddArticleDto();
            BeanUtils.copyProperties(item,yddArticleDto);
            YddCate cate = yddCateService.getById(item.getCateid());
            yddArticleDto.setCatename(cate.getCatename());
            return yddArticleDto;
        }).collect(Collectors.toList());

        hashMap.put("data",data);
        map.put("list",hashMap);
        return R.success(map);
    }

    //文章列表数据
    @GetMapping("/list")
    public R<HashMap> allarticle(int page, int limit,int cateid){
        log.info("文章列表数据请求：page="+page+";limit="+limit+";cateid="+cateid);
        HashMap hashMap = yddArticleService.allArticle(page, limit, cateid);
        return R.success(hashMap);
    }
    //最新文章
    @GetMapping("/hot")
    public R newarticle(){
        //构造条件构造器
        /*QueryWrapper<YddArticle> articleWrapper = new QueryWrapper<>();
        articleWrapper.lambda().select(YddArticle::getCateid,YddArticle::getId,YddArticle::getTitle,YddArticle::getPic,YddArticle::getLovenum);*/
        LambdaQueryWrapper<YddArticle> articleWrapper = new LambdaQueryWrapper<>();
        articleWrapper.select(YddArticle::getCateid,YddArticle::getId,YddArticle::getTitle,YddArticle::getPic,YddArticle::getLovenum);

        //执行查询
        List<YddArticle> yddArticles = yddArticleService.list(articleWrapper);
        //添加额外catename字段
        List<YddArticleDto> list = yddArticles.stream().map((item)->{
        YddArticleDto articleDto = new YddArticleDto();
        BeanUtils.copyProperties(item,articleDto);

        YddCate cate = yddCateService.getById(item.getCateid());
        articleDto.setCatename(cate.getCatename());
        return articleDto;
        }).collect(Collectors.toList());

        ArrayList<YddArticleDto> dtos = new ArrayList<>();
        int a=0;
        for (YddArticleDto dto : list) {
            if (a<6){
                dtos.add(dto);
                a++;
            }else {
                break;
            }
        }
        //创建map集合
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("desc","侧边最新文章");
        hashMap.put("list",dtos);
        //创建List集合

        return R.success(hashMap);

    }
    //推荐文章
    @GetMapping("/recommend")
    public R recommend(){

        //构造条件构造器
        LambdaQueryWrapper<YddArticle> articleWrapper = new LambdaQueryWrapper<>();
        articleWrapper.select(YddArticle::getCateid,YddArticle::getId,YddArticle::getTitle,YddArticle::getPic,YddArticle::getLovenum,YddArticle::getClick);

        //执行查询
        List<YddArticle> yddArticles = yddArticleService.list(articleWrapper);
        //添加额外catename字段
        List<YddArticleDto> list = yddArticles.stream().map((item)->{
            YddArticleDto articleDto = new YddArticleDto();
            BeanUtils.copyProperties(item,articleDto);
            YddCate yddCate = yddCateService.getById(item.getCateid());
            articleDto.setCatename(yddCate.getCatename());
            return articleDto;
        }).collect(Collectors.toList());
        //创建List集合
        ArrayList<YddArticleDto> dtos = new ArrayList<>();
        int a=0;
        for (YddArticleDto dto : list) {
            if (a<6){
                dtos.add(dto);
                a++;
            }else {
                break;
            }
        }
        //创建map集合
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("desc","侧边推荐文章");
        hashMap.put("list",dtos);

        return R.success(hashMap);

    }

    @PostMapping("/reg")
    public R reg(@RequestBody YddUser yddUser){
        String mobile = yddUser.getMobile();
        String password=yddUser.getPassword();
        LambdaQueryWrapper<YddUser> phoneQw=new LambdaQueryWrapper();
        phoneQw.eq(YddUser::getMobile,mobile);
        YddUser user = yddUserService.getOne(phoneQw);
        if (user!=null){
            return R.error("账号已存在,请登录");
        }

        password= DigestUtils.md5DigestAsHex(password.getBytes());
        yddUser.setPassword(password);
        yddUser.setUsername(mobile);
        yddUserService.save(yddUser);

        HashMap hashMap = new HashMap<>();
        hashMap.put("id",yddUser.getId());
        String token = JwtUtils.getToken(hashMap);

        HashMap<String, String> map = new HashMap<>();
        map.put("token",token);

        return R.success(map);
    }
}

